前端analysis | What,Why,Who,When,Where,How

《Performance》- web-worker 深入了解

2020-12-09

web-worker

通信过程

web api支持情况

不支持的web api

  • window
  • document

支持的

  • navigator

  • Console API

  • CustomEvent

  • Promise

  • websocket

  • ajax XMLHttpRequest

  • location(read-only)

  • setTimeout、clearTimeout、setInterval、clearInterval

  • atob()、btoa()

  • Cache对象(IE不支持)

  • IndexedDB

webworker 会内存泄漏吗?

worker是new创建的,在angular destory中,webworker依旧处于监听状态,如果不销毁,会存在内存泄漏

1
const worker = new Worker('./hello.worker', { type: 'module' });

postMessage可以传递哪些参数?

  • 字符串
  • 对象,但是对象方法会移除,
  • 数组
  • 函数,直接异常

如何终止webWorker

1
2
# 调用即立刻终止
worker.terminate()

在angular开发中,我们需要手动关闭worker

1
2
3
4
ngDestory(){
worker.terminate()
}

URL 创建webworker

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
private readonly worker: Worker;
private onMessage = new Subject<MessageEvent>();
private onError = new Subject<ErrorEvent>();

constructor(func) {

const WORKER_ENABLED = !!(Worker);

if (WORKER_ENABLED) {
const functionBody = func.toString().replace(/^[^{]*{\s*/, '').replace(/\s*}[^}]*$/, '');

this.worker = new Worker(URL.createObjectURL(
new Blob([ functionBody ], { type: 'text/javascript' })
));

this.worker.onmessage = (data) => {
this.onMessage.next(data);
};

this.worker.onerror = (data) => {
this.onError.next(data);
};

} else {
throw new Error('WebWorker is not enabled');
}
}

postMessage(data) {
this.worker.postMessage(data);
}

onmessage(): Observable<MessageEvent> {
return this.onMessage.asObservable();
}

onerror(): Observable<ErrorEvent> {
return this.onError.asObservable();
}

terminate() {
if (this.worker) {
this.worker.terminate();
}
}

new worker

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
 const worker = new InlineWorker(() => {
// START OF WORKER THREAD CODE
console.log('Start worker thread, wait for postMessage: ');

const calculateCountOfPrimeNumbers = (limit) => {

const isPrime = num => {
for (let i = 2; i < num; i++) {
if (num % i === 0) { return false; }
}
return num > 1;
};

let countPrimeNumbers = 0;

while (limit >= 0) {
if (isPrime(limit)) { countPrimeNumbers += 1; }
limit--;
}

// this is from DedicatedWorkerGlobalScope ( because of that we have postMessage and onmessage methods )
// and it can't see methods of this class
// @ts-ignore
this.postMessage({
primeNumbers: countPrimeNumbers
});
};

// @ts-ignore
this.onmessage = (evt) => {
console.log('Calculation started: ' + new Date());
calculateCountOfPrimeNumbers(evt.data.limit);
};
// END OF WORKER THREAD CODE
});

webWorker可以无限制传递数据?

参考

Using_web_workers
whats-new-in-angular-8-web-worker-support-and-more
Angular Deprecations
JavaScript modules can improve performance

使用支付宝打赏
使用微信打赏

若你觉得我的文章对你有帮助,欢迎点击上方按钮对我打赏